package facade;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class Controleur
{
	public Facade face;
	public String ConnectURL;
	public Connection connection, connection_2;
	public DatabaseMetaData dbMeta;
	public Statement statement, statement_2;
	public ResultSet resultset, resultset_2;

	public void dbConnect() throws Exception
	{
		// Connection a la database MySQL
		Class.forName("com.mysql.jdbc.Driver");
		ConnectURL = "jdbc:mysql://localhost:3306/dorian";
		connection = DriverManager.getConnection(ConnectURL, "root", "");
		connection_2 = DriverManager.getConnection(ConnectURL, "root", "");
		dbMeta = connection.getMetaData();
		// Declaration Statement et ResultSet
		statement = connection.createStatement();
		statement_2 = connection_2.createStatement();
	}
	
	public void dbDisconnect() throws Exception
	{
		statement.close();
		statement_2.close();
		connection.close();
		connection_2.close();
	}
	
	public ResultSet GenerateRS(String Query) throws Exception
	{
		Statement state = connection.createStatement();
		ResultSet result = state.executeQuery(Query);
		return (result);
	}
	
	public void setQueryResultSet(String Query) throws Exception
	{
			resultset = statement.executeQuery(Query);
	}
	
	public String getConfigField(String field) throws Exception
	{
		Statement state = connection.createStatement();
		String Query = "SELECT * FROM `Config`;";
		ResultSet result = state.executeQuery(Query);
		String value = "";
		while (result.next())
		{
			if (result.getString(2).contentEquals(field))
			 value = result.getString(3);
		}
		state.close();
		return value;
	}
	
	public void setConfigField(String var, String value) throws Exception
	{
		Statement state = connection.createStatement();
		String Query = "SELECT * FROM `Config` WHERE `Variable` = \"" + var + "\";";
		ResultSet result = state.executeQuery(Query);
		if (result.next())
			state.execute("UPDATE `Config` SET `Value` = \"" + value + "\" WHERE `Variable` = \"" + var + "\";");
		else
			state.execute("INSERT INTO `Config` (`Variable`,`Value`) VALUES(\"" + var +"\", \""+ value + "\");");
		state.close();
	}
	
	public Integer getValidId(String table) throws Exception
	{
		Integer id = 1;
		ResultSet rs = GenerateRS("SELECT Id FROM `" + table + "`;");
		while (rs.next())
			id = rs.getInt(1);
		id++;
		return id;
	}
}